package com.example.dynamicschedule.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.dynamicschedule.bean.CustomerClassEnum;
import com.example.dynamicschedule.bean.HttpClientResult;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class HttpClientUtils {
    /**
     * 信贷规则
     * @param rulesPath
     * @param postParam
     * @return
     * @throws Exception
     */
    public static Map<String, String> getCreditPostRules(String rulesPath, Map<String, String> postParam)throws  Exception{
        Map<String, String> resultMap = new HashMap<>();
        HttpClientResult httpClientResult = doPost(rulesPath, postParam);
        int code = httpClientResult.getCode();
        if (code != 200) {
            resultMap.put("outbound","0");
            return resultMap;
        }
        String content = httpClientResult.getContent();
        JSONObject jsonObject = JSON.parseObject(content);
        //outbound 输出三方外呼的结果
        Object outbound = jsonObject.get("outbound");
        JSONObject outboundJsonObject = JSON.parseObject(String.valueOf(outbound));
        Object outbound2 = outboundJsonObject.get("outbound");
        if (StringUtils.isNotEmpty(String.valueOf(outbound2))) {
            //风险等级
            Object riskLevel = jsonObject.get("riskLevel");
            JSONObject riskLevelObject = JSON.parseObject(String.valueOf(riskLevel));
            Object riskLevel1 = riskLevelObject.get("riskLevel");
            String riskLevelStr = String.valueOf(riskLevel1);
            String riskLevelChinese=null;
            if ("1".equalsIgnoreCase(riskLevelStr)) {
                riskLevelChinese="高风险";
            } else if ("2".equalsIgnoreCase(riskLevelStr)) {
                riskLevelChinese="中风险";
            } else if ("3".equalsIgnoreCase(riskLevelStr)) {
                riskLevelChinese="低风险";
            }
            resultMap.put("riskLevel",riskLevelChinese);
            //下次下发时间
            Object norm = jsonObject.get("resful");
            JSONObject normObject = JSON.parseObject(String.valueOf(norm));
            Object norm1 = normObject.get("norm");
            String normStr = String.valueOf(norm1);
            resultMap.put("norm",normStr);
        }
        resultMap.put("outbound",String.valueOf(outbound2));
        if (outbound2 != null) {
            return resultMap;
        }else {
            resultMap.put("outbound","0");
            return resultMap;
        }
    }
    /**
     * 规则的处理
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static Map<String, String> getPostRules(String url, Map<String, String> params) throws IOException{
        Map<String, String> resultMap = new HashMap<>();
        HttpClientResult httpClientResult = doPost(url, params);
        int code = httpClientResult.getCode();
        if (code != 200) {
            resultMap.put("outbound","0");
            return resultMap;
        }
        String content = httpClientResult.getContent();
        JSONObject jsonObject = JSON.parseObject(content);
        //outbound 输出三方外呼的结果
        Object outbound = jsonObject.get("outbound");
        JSONObject outboundJsonObject = JSON.parseObject(String.valueOf(outbound));
        Object outbound2 = outboundJsonObject.get("outbound");
        //如果为短信结果,短信模板的获取
        if (String.valueOf(outbound2).contains("1")) {
            Object note = jsonObject.get("note");
            JSONObject noteJsonObject = JSON.parseObject(String.valueOf(note));
            Object note2 = noteJsonObject.get("node");
            resultMap.put("note",String.valueOf(note2));
        }
        if (StringUtils.isNotEmpty(String.valueOf(outbound2))) {
            //客群分类
            Object customersClassify = jsonObject.get("CustomersClassify");
            JSONObject customersClassifyObject = JSON.parseObject(String.valueOf(customersClassify));
            Object customersClassify1 = customersClassifyObject.get("CustomersClassify");
            String customersClassifyStr = String.valueOf(customersClassify1);
            String customersClassifyChinese = getCustomersClassifyChinese(customersClassifyStr);
            resultMap.put("CustomersClassify",customersClassifyChinese);
            //风险等级
            Object riskLevel = jsonObject.get("riskLevel");
            JSONObject riskLevelObject = JSON.parseObject(String.valueOf(riskLevel));
            Object riskLevel1 = riskLevelObject.get("riskLevel");
            String riskLevelStr = String.valueOf(riskLevel1);
            String riskLevelChinese=null;
            if ("1".equalsIgnoreCase(riskLevelStr)) {
                riskLevelChinese="高风险";
            } else if ("2".equalsIgnoreCase(riskLevelStr)) {
                riskLevelChinese="中风险";
            } else if ("3".equalsIgnoreCase(riskLevelStr)) {
                riskLevelChinese="低风险";
            }
            resultMap.put("riskLevel",riskLevelChinese);
        }

        resultMap.put("outbound",String.valueOf(outbound2));
        if (outbound2 != null) {
            return resultMap;
        }else {
            resultMap.put("outbound","0");
            return resultMap;
        }
    }

    private static String getCustomersClassifyChinese(String customersClassifyStr) {
        String customerClassStr=null;
        switch (customersClassifyStr) {
            case "1":
                customerClassStr=CustomerClassEnum.CustomerClassEnum1.getDesc();
                break;
            case "2":
                customerClassStr=CustomerClassEnum.CustomerClassEnum2.getDesc();
                break;
            case "3":
                customerClassStr=CustomerClassEnum.CustomerClassEnum3.getDesc();
                break;
            case "4":
                customerClassStr=CustomerClassEnum.CustomerClassEnum4.getDesc();
                break;
            case "5":
                customerClassStr=CustomerClassEnum.CustomerClassEnum5.getDesc();
                break;
            case "6":
                customerClassStr=CustomerClassEnum.CustomerClassEnum6.getDesc();
                break;
            case "7":
                customerClassStr=CustomerClassEnum.CustomerClassEnum7.getDesc();
                break;
            case "8":
                customerClassStr=CustomerClassEnum.CustomerClassEnum8.getDesc();
                break;
            case "9":
                customerClassStr=CustomerClassEnum.CustomerClassEnum9.getDesc();
                break;
            case "10":
                customerClassStr=CustomerClassEnum.CustomerClassEnum10.getDesc();
                break;
            case "11":
                customerClassStr=CustomerClassEnum.CustomerClassEnum11.getDesc();
                break;
            case "12":
                customerClassStr=CustomerClassEnum.CustomerClassEnum12.getDesc();
                break;
            case "13":
                customerClassStr=CustomerClassEnum.CustomerClassEnum13.getDesc();
                break;
            case "14":
                customerClassStr=CustomerClassEnum.CustomerClassEnum14.getDesc();
                break;
            case "15":
                customerClassStr=CustomerClassEnum.CustomerClassEnum15.getDesc();
                break;
            case "16":
                customerClassStr=CustomerClassEnum.CustomerClassEnum16.getDesc();
                break;
            case "17":
                customerClassStr=CustomerClassEnum.CustomerClassEnum17.getDesc();
                break;
            case "18":
                customerClassStr=CustomerClassEnum.CustomerClassEnum18.getDesc();
                break;
            case "19":
                customerClassStr=CustomerClassEnum.CustomerClassEnum19.getDesc();
                break;
            case "20":
                customerClassStr=CustomerClassEnum.CustomerClassEnum20.getDesc();
                break;
            case "21":
                customerClassStr=CustomerClassEnum.CustomerClassEnum21.getDesc();
                break;
            case "22":
                customerClassStr=CustomerClassEnum.CustomerClassEnum22.getDesc();
                break;
            case "23":
                customerClassStr=CustomerClassEnum.CustomerClassEnum23.getDesc();
                break;
            case "24":
                customerClassStr=CustomerClassEnum.CustomerClassEnum24.getDesc();
                break;
            case "25":
                customerClassStr=CustomerClassEnum.CustomerClassEnum25.getDesc();
                break;
            case "26":
                customerClassStr=CustomerClassEnum.CustomerClassEnum26.getDesc();
                break;
            case "27":
                customerClassStr=CustomerClassEnum.CustomerClassEnum27.getDesc();
                break;
        }
        return customerClassStr;
    }

    /**
     * 规则请求
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    private static HttpClientResult doPost(String url, Map<String, String> params) throws IOException {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        // 封装请求参数
        packageParam(params, httpPost);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    private static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws ClientProtocolException, IOException {
        // 执行请求
        httpResponse = httpClient.execute(httpMethod);
        String content = "";
        // // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {

            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                System.out.println("=====" + content);
            }
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

    private static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        }
    }


}

